package com.huishu.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huishu.commons.config.cache.RedisUtil;
import com.huishu.commons.constant.RedisKeyPrefix;
import com.huishu.commons.exception.BaseException;
import com.huishu.commons.pojo.BasePage;
import com.huishu.commons.pojo.Result;
import com.huishu.commons.utlis.BeanUtils;
import com.huishu.goods.mapper.GiveMapper;
import com.huishu.goods.mapper.MaterialBenefitsMapper;
import com.huishu.goods.pojo.dto.FindWelfareDTO;
import com.huishu.goods.pojo.dto.MaterialBenefitsCreateDTO;
import com.huishu.goods.pojo.dto.MaterialBenefitsUpdateDTO;
import com.huishu.goods.pojo.model.GiveDO;
import com.huishu.goods.pojo.model.MaterialBenefitsDO;
import com.huishu.goods.pojo.model.MaterialBenefitsProductGiveDO;
import com.huishu.goods.pojo.vo.MaterialBenefitsFindVO;
import com.huishu.goods.pojo.vo.MaterialBenefitsPageVO;
import com.huishu.goods.pojo.vo.MaterialBenefitsProductGiveVO;
import com.huishu.goods.pojo.vo.MaterialBenefitsVO;
import com.huishu.goods.service.MaterialBenefitsProductGiveService;
import com.huishu.goods.service.MaterialBenefitsService;
import com.huishu.goods.utils.AssistantContext;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author generator@ljj
 * @since 2023-04-12
 */
@Service
public class MaterialBenefitsServiceImpl extends ServiceImpl<MaterialBenefitsMapper, MaterialBenefitsDO> implements MaterialBenefitsService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private MaterialBenefitsProductGiveService materialBenefitsProductGiveService;

    @Autowired
    private GiveMapper giveMapper;

    @Override
    public Result findWelfare(FindWelfareDTO findWelfareDTO) {
        String value = redisUtil.getString(RedisKeyPrefix.WELFARE_CODE + findWelfareDTO.getWelfareCode() + ":" + AssistantContext.getCurrentUid());
        if (StringUtils.isEmpty(value)) {
            LambdaQueryWrapper<MaterialBenefitsDO> queryWrapper = Wrappers.lambdaQuery(MaterialBenefitsDO.class)
                    .eq(MaterialBenefitsDO::getIsOpen, 1)
                    .eq(MaterialBenefitsDO::getWelfareCode, findWelfareDTO.getWelfareCode());
            MaterialBenefitsDO materialBenefitsDO = this.getOne(queryWrapper);
            if (materialBenefitsDO == null) {
                return Result.success();
            }
            if(findWelfareDTO.getAmount().compareTo(materialBenefitsDO.getSatisfiedAmount()) == -1){
                return Result.fail("当前口令不符合使用条件！");
            }
            LambdaQueryWrapper<MaterialBenefitsProductGiveDO> queryWrapperMaterialBenefitsProductGive = Wrappers.lambdaQuery(MaterialBenefitsProductGiveDO.class)
                    .eq(MaterialBenefitsProductGiveDO::getWelfareCode, findWelfareDTO.getWelfareCode());
            List<MaterialBenefitsProductGiveDO> materialBenefitsProductGives = materialBenefitsProductGiveService.list(queryWrapperMaterialBenefitsProductGive);
            if (CollectionUtils.isEmpty(materialBenefitsProductGives)) {
                return Result.success();
            }
            Map<Long, MaterialBenefitsProductGiveDO> materialBenefitsProductGiveMap = materialBenefitsProductGives.parallelStream().collect(Collectors.toMap(MaterialBenefitsProductGiveDO::getGiveProductId, p -> p));
            List<Long> giveProductId = materialBenefitsProductGives.stream().map(MaterialBenefitsProductGiveDO::getGiveProductId).collect(Collectors.toList());

            LambdaQueryWrapper<GiveDO> queryWrapper1 = Wrappers.lambdaQuery(GiveDO.class)
                    .in(GiveDO::getId, giveProductId);
            List<GiveDO> gives = giveMapper.selectList(queryWrapper1);
            MaterialBenefitsVO materialBenefitsVO = new MaterialBenefitsVO();
            materialBenefitsVO.setContent(materialBenefitsDO.getContent());
            materialBenefitsVO.setWelfareCode(findWelfareDTO.getWelfareCode());
            if (CollectionUtils.isNotEmpty(gives)) {
                List<MaterialBenefitsProductGiveVO> collect = gives.stream().map(give -> {
                    MaterialBenefitsProductGiveVO materialBenefitsProductGiveVO = new MaterialBenefitsProductGiveVO();
                    materialBenefitsProductGiveVO.setGiveProductId(give.getId());
                    materialBenefitsProductGiveVO.setGiveProductSku(give.getSkuCode());
                    materialBenefitsProductGiveVO.setName(give.getName());
                    materialBenefitsProductGiveVO.setDisplayDrawingPics(give.getDisplayDrawingPics());
                    MaterialBenefitsProductGiveDO materialBenefitsProductGiveDO = materialBenefitsProductGiveMap.get(give.getId());
                    materialBenefitsProductGiveVO.setNum(materialBenefitsProductGiveDO.getNum());
                    return materialBenefitsProductGiveVO;
                }).collect(Collectors.toList());
                materialBenefitsVO.setMaterialBenefitsProductGives(collect);
            }
            return Result.success(materialBenefitsVO);
        }
        return Result.fail("您已经使用过该福利码了！");
    }

    @Override
    public Result pageList(BasePage basePage) {
        Page<MaterialBenefitsPageVO> page = new Page<>(basePage.getCurrPage(), basePage.getPageSize());
        return Result.success(this.baseMapper.pageList(page, basePage));
    }

    @Transactional
    @Override
    public Result create(MaterialBenefitsCreateDTO materialBenefitsCreateDTO) {
        LambdaQueryWrapper<MaterialBenefitsDO> queryWrapper = Wrappers.lambdaQuery(MaterialBenefitsDO.class)
                .eq(MaterialBenefitsDO::getWelfareCode, materialBenefitsCreateDTO.getWelfareCode());
        MaterialBenefitsDO one = this.getOne(queryWrapper);
        if (one != null) {
            return Result.fail("请勿添加重复福利码!!");
        }
        MaterialBenefitsDO materialBenefitsDO = BeanUtils.copyProperties(materialBenefitsCreateDTO, MaterialBenefitsDO.class);
        boolean save = this.save(materialBenefitsDO);
        if (!save) {
            throw new BaseException("添加失败!!");
        }
        List<MaterialBenefitsProductGiveDO> collect = materialBenefitsCreateDTO.getMaterialBenefitsProductGives().stream().map(materialBenefitsProductGiveDO -> materialBenefitsProductGiveDO.setWelfareCode(materialBenefitsCreateDTO.getWelfareCode())).collect(Collectors.toList());
        return materialBenefitsProductGiveService.saveBatch(collect) ? Result.success() : Result.fail();
    }

    @Override
    public Result modify(MaterialBenefitsUpdateDTO materialBenefitsUpdateDTO) {
        LambdaQueryWrapper<MaterialBenefitsDO> queryWrapper = Wrappers.lambdaQuery(MaterialBenefitsDO.class)
                .eq(MaterialBenefitsDO::getWelfareCode, materialBenefitsUpdateDTO.getWelfareCode())
                .ne(MaterialBenefitsDO::getId, materialBenefitsUpdateDTO.getId());
        MaterialBenefitsDO one = this.getOne(queryWrapper);
        if (one != null) {
            return Result.fail("请勿添加重复福利码!!");
        }
        MaterialBenefitsDO materialBenefitsDO = BeanUtils.copyProperties(materialBenefitsUpdateDTO, MaterialBenefitsDO.class);
        boolean save = this.updateById(materialBenefitsDO);
        if (!save) {
            throw new BaseException("添加失败!!");
        }
        LambdaQueryWrapper<MaterialBenefitsProductGiveDO> qw = Wrappers.lambdaQuery(MaterialBenefitsProductGiveDO.class)
                .eq(MaterialBenefitsProductGiveDO::getWelfareCode, materialBenefitsUpdateDTO.getWelfareCode());
        materialBenefitsProductGiveService.remove(qw);
        List<MaterialBenefitsProductGiveDO> collect = materialBenefitsUpdateDTO.getMaterialBenefitsProductGives().stream().map(materialBenefitsProductGiveDO -> materialBenefitsProductGiveDO.setWelfareCode(materialBenefitsUpdateDTO.getWelfareCode())).collect(Collectors.toList());
        return materialBenefitsProductGiveService.saveBatch(collect) ? Result.success() : Result.fail();
    }


    @Override
    public Result findById(Long id) {
        MaterialBenefitsDO materialBenefitsDO = this.getById(id);
        MaterialBenefitsFindVO materialBenefitsFindVO = BeanUtils.copyProperties(materialBenefitsDO, MaterialBenefitsFindVO.class);
        LambdaQueryWrapper<MaterialBenefitsProductGiveDO> qw = Wrappers.lambdaQuery(MaterialBenefitsProductGiveDO.class)
                .eq(MaterialBenefitsProductGiveDO::getWelfareCode, materialBenefitsDO.getWelfareCode());
        materialBenefitsFindVO.setMaterialBenefitsProductGives(materialBenefitsProductGiveService.list(qw));
        return Result.success(materialBenefitsFindVO);
    }

    @Override
    public Result delete(Long id) {
        MaterialBenefitsDO materialBenefitsDO = this.getById(id);
        this.removeById(id);
        LambdaQueryWrapper<MaterialBenefitsProductGiveDO> qw = Wrappers.lambdaQuery(MaterialBenefitsProductGiveDO.class)
                .eq(MaterialBenefitsProductGiveDO::getWelfareCode, materialBenefitsDO.getWelfareCode());
        materialBenefitsProductGiveService.remove(qw);
        return Result.success();
    }
}
